$(function() {
	$.validator.addMethod("checkUsername", function(value, element) {
		return this.optional(element) || /^[a-zA-Z][a-zA-Z0-9_]+$/.test(value);
	}, "用户名格式不正确");

	$.validator.addMethod("checkPassword", function(value, element) {
		return this.optional(element)
				|| /^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]+$/.test(value);
	}, "密码格式不正确");

	$("#registerForm").validate({
		errorElement : "em",
		rules : {
			username : {
				required : true,
				rangelength : [ 6, 16 ],
				checkUsername : true,
				remote : "exist-username.do"
			},
			password : {
				required : true,
				rangelength : [ 6, 16 ],
				checkPassword : true
			},
			confirmPassword : {
				required : true,
				equalTo : "#password"
			},
			email : {
				required : true,
				rangelength : [ 3, 60 ],
				email : true,
				remote : "exist-email.do"
			},
			captcha : {
				required : true,
				remote : "validate-captcha.do"
			},
			agreement : {
				required : true
			}
		},
		messages : {
			username : {
				required : "用户名不能为空",
				rangelength : "用户名只能在6到16位之间",
				checkUsername : "用户名格式不正确",
				remote : $.format("用户名{0}已存在，请重新输入！")
			},
			password : {
				required : "密码不能为空",
				rangelength : "密码只能在6到16位之间",
				checkPassword : "密码格式不正确"
			},
			confirmPassword : {
				required : "确认密码不能为空",
				equalTo : "确认密码和密码不符"
			},
			email : {
				required : "邮箱地址不能为空",
				rangelength : "邮箱地址只能在3到60位之间",
				email : "不是一个有效的电邮地址",
				remote : $.format("邮箱地址{0}已存在，请重新输入！")
			},
			captcha : {
				required : "验证码不能为空",
				remote : "验证码错误"
			},
			agreement : {
				required : "必须同意注册协议"
			}
		},
		errorPlacement : function(error, element) {
			var errorObj = element.parent().children("span.f_red");
			if (errorObj && (typeof errorObj.text == "function"))
				errorObj.text("");
			if (errorObj && (typeof errorObj.html == "function"))
				errorObj.html("");
			error.appendTo(errorObj);
		},
		success : function(element) {
			if (element && (typeof element.text == "function"))
				element.text("");
			if (element && (typeof element.html == "function"))
				element.html("");
		}
	});

	// 切换验证码
	$('#reload_captcha').click(function() {
		var src = $('#captcha_image').attr('src');
		var p = src.indexOf('?');
		var newSrc = null;
		if (p > 0) {
			newSrc = src.substring(0, p) + '?' + Math.random();
		} else {
			newSrc = src + '?' + Math.random();
		}
		$('#captcha_image').attr('src', newSrc);
	});
});